import {BaseInfoWrapper, Wrapper} from './style.ts'
import TeacherMyClassRoomNav from "@/pages/TeacherMyClassRoom/TeacherMyClassRoomNav";
import {Button, DatePicker, Dropdown, Form, Input, MenuProps, Modal, Select, Tabs, TabsProps} from "antd";
import ClassCard from "@/pages/TeacherMyClassRoom/ClassCard";
import search from "@/static/imgs/TeacherMyClassroom/搜索 (1).svg";
import {useEffect, useState} from "react";
import ClassBox from "@/pages/TeacherMyClassRoom/ClassBox";
import {
    addCourse,
    changeArchive,
    getArchiveCourse,
    getLearnCourse,
    getTeachCourse,
    getTopCourse
} from "@/api/teacher/courseApi.ts";
import ArchiveManagement from "@/components/ArchiveManagement";

interface Course {
    title: string;
    course: any;
}

function categorizeCourses(data: any) {
    const result: any = {};

    data.forEach((course: any) => {
        const title = `${course.semester} ${course.academicYear}`;
        if (!result[title]) {
            result[title] = [];
        }

        result[title].push(course);
    });

    const categorizedCourses = Object.keys(result).map(title => ({
        title: title,
        course: result[title]
    }));

    return categorizedCourses;
}

const TeacherMyClassRoom = () => {

    const [topCourse, setTopCourse] = useState([]); // 置顶课程
    const [myCourse, setMyCourse] = useState<Course[]>(); // 我教的课程
    const [learnCourse, setLearnCourse] = useState<Course[]>(); // 我学的课程
    const [archiveCourse, setArchiveCourse] = useState<Course[]>(); // 归档课程
    const [isArchivedChange, setIsArchivedChange] = useState(false)
    useEffect(() => {
        if (isArchivedChange) {
            initCourse()
            setIsArchivedChange(false)
        }
    }, [isArchivedChange])
    const initCourse = () => {
        getTopCourse().then(res => {
            setTopCourse(res.data.data)
        })
        getTeachCourse().then(res => {
            const teachClass = res.data.data
            setMyCourse(categorizeCourses(teachClass))
        })
        getLearnCourse().then(res => {
            const learningClass = res.data.data
            setLearnCourse(categorizeCourses(learningClass))
        })
        getArchiveCourse().then(res => {
            const archiveClass = res.data.data
            setArchiveCourse(categorizeCourses(archiveClass))
        })
    }

    useEffect(() => {
        initCourse()
    }, [])

    const onChange = (key: string) => {
        console.log(key);
    };

    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '我教的',
            children: (
                <>
                    {
                        myCourse?.map((item: any) => {
                            return <ClassBox title={item.title}>
                                {item.course.map((item: any) => {
                                    return <ClassCard key={item.id} courseId={item.id} academicYear={item.academicYear}
                                                      semester={item.semester}
                                                      name={item.name} teachClass={item.teachClass} code={item.code}
                                                      userName={item.createUser}
                                                      bg={item.bg}
                                                      isTop={item.isTop}
                                                      isArchived={item.isArchived}
                                                      initCourse={initCourse}
                                    />
                                })}
                            </ClassBox>
                        })
                    }
                </>
            ),
        },
        {
            key: '2',
            label: '我学的',
            children: (
                <>
                    {
                        learnCourse?.map((item: any) => {
                            return <ClassBox title={item.title}>
                                {item.course.map((item: any) => {
                                    return <ClassCard key={item.id} courseId={item.id} academicYear={item.academicYear}
                                                      semester={item.semester}
                                                      name={item.name} teachClass={item.teachClass} code={item.code}
                                                      userName={item.createUser}
                                                      bg={item.bg}
                                                      isTop={item.isTop}
                                                      isArchived={item.isArchived}
                                                      initCourse={initCourse}
                                    />
                                })}
                            </ClassBox>
                        })
                    }
                </>
            ),
        },
    ];

    //创建课程窗口
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        form.validateFields().then(() => {
            console.log(form.getFieldsValue());
            const data = {
                ...form.getFieldsValue(),
                academicYear: form.getFieldsValue().academicYear[0].format('YYYY') + '-' + form.getFieldsValue().academicYear[1].format('YYYY'),
            }
            addCourse(data).then(() => {
                initCourse()
            })
            setIsModalOpen(false);
        }).catch((errorInfo) => {
            console.log(errorInfo);
        })

    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };


    // 创建课程基本信息表单
    const [form] = Form.useForm();


    const onCourseChange = (key: string) => {
        console.log(key);
    };

    const {RangePicker} = DatePicker;

    const BaseCourseInfo = () => {
        return (
            <div>
                <Form
                    form={form}
                    name="addCourse"
                    autoComplete="off"
                >
                    <Form.Item
                        label="课程名称"
                        name="name"
                        rules={[{required: true, message: '请输入课程名称'}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="教学班级"
                        name="teachClass"
                        rules={[{required: true, message: '请输入教学班级'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <BaseInfoWrapper>
                        <div className='base-info-last'>
                            <div>选择学年-学期</div>
                            <Form.Item
                                name="academicYear"
                            >
                                <RangePicker
                                    picker="year"
                                    id={{
                                        start: 'startInput',
                                        end: 'endInput',
                                    }}
                                    onFocus={(_, info) => {
                                        console.log('Focus:', info.range);
                                    }}
                                    onBlur={(_, info) => {
                                        console.log('Blur:', info.range);
                                    }}
                                />
                            </Form.Item>
                            <Form.Item
                                name="semester"
                            >
                                <Select
                                    placeholder="请选择学期"
                                    style={{width: 120}}
                                    allowClear
                                    options={[{value: '第一学期', label: '第一学期'}, {
                                        value: '第二学期',
                                        label: '第二学期'
                                    }]}
                                />
                            </Form.Item>
                        </div>
                    </BaseInfoWrapper>
                </Form>
            </div>
        )
    }

    const addCourseItems: TabsProps['items'] = [
        {
            key: '1',
            label: '基本信息(必填)',
            children: <BaseCourseInfo/>,
        },
        {
            key: '2',
            label: '报名设置',
            children: 'Content of Tab Pane 2',
        },
    ];

    const dropDownItems: MenuProps['items'] = [
        {
            key: '1',
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={() => showModal()}>
                    创建课程
                </a>
            ),
        },
        {
            key: '2',
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={() => {
                    showAddModal()
                }}>
                    加入课程
                </a>
            ),
        },
    ];

    const [isAddModalOpen, setIsAddModalOpen] = useState(false);

    const showAddModal = () => {
        setIsAddModalOpen(true);
    };

    const handleAddOk = () => {
        setIsAddModalOpen(false);
    };

    const handleAddCancel = () => {
        setIsAddModalOpen(false);
    };

    const [addForm] = Form.useForm();

    const [isArchivedModelOpen, setIsArchivedModelOpen] = useState(false);
    const showArchivedModel = () => {
        console.log(archiveCourse)
        setIsArchivedModelOpen(true);
    };
    const handleArchivedOk = () => {
        setIsArchivedModelOpen(false);
    }
    const handleArchivedCancel = () => {
        initCourse()
        setIsArchivedModelOpen(false);
    }

    return (
        <Wrapper>
            <TeacherMyClassRoomNav/>
            <Modal title="归档管理" open={isArchivedModelOpen} onOk={handleArchivedOk} cancelText={'取消'}
                   onCancel={handleArchivedCancel}
                   okText={'确认'}
                   width={700}
            >
                <ArchiveManagement archiveCourse={archiveCourse} setIsArchivedChange={setIsArchivedChange}
                                   changeArchive={changeArchive}/>
            </Modal>

            <Modal title="加入课程" open={isAddModalOpen} onOk={handleAddOk} onCancel={handleAddCancel}
                   cancelText={'取消'}
                   okText={'确认'}>
                <Form
                    form={addForm}
                    name="basic"
                    autoComplete="off"
                >
                    <Form.Item
                        label="课程码"
                        name="code"
                        rules={[{required: true, message: '请输入课程码!'}]}
                    >
                        <Input placeholder={'请输入课程加课码'}/>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal title="创建课程" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} cancelText={'取消'}
                   okText={'确认'}
                   width={'700px'}>
                <Tabs defaultActiveKey="1" items={addCourseItems} onChange={onCourseChange}/>
            </Modal>
            <div className="home">
                <div className="content">
                    <div className="header">
                        <div className="top-handler">
                            <h2 className="left">置顶课程</h2>
                            <Dropdown menu={{items: dropDownItems}} trigger={['click']} arrow
                                      placement={'bottomCenter'}>
                                <Button type="primary">+创建/加入课程</Button>
                            </Dropdown>
                        </div>
                        <div className="class-box">
                            {
                                topCourse.map((item: any) => {
                                    return <ClassCard key={item.id} courseId={item.id} academicYear={item.academicYear}
                                                      semester={item.semester}
                                                      name={item.name} teachClass={item.teachClass} code={item.code}
                                                      userName={item.createUser}
                                                      bg={item.bg}
                                                      isTop={item.isTop}
                                                      isArchived={item.isArchived}
                                                      initCourse={initCourse}
                                    />
                                })
                            }
                        </div>
                    </div>

                    <div className="other-header">
                        <div className="left">
                            <Tabs defaultActiveKey="1" items={items} onChange={onChange}/>
                        </div>
                        <div className="right">
                            <Button onClick={showArchivedModel}>归档管理</Button>
                            <div className="search">
                                <input type="text" placeholder={'搜索我教的课程'}/>
                                <img src={search} alt=""/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Wrapper>
    );
}
export default TeacherMyClassRoom;